<template>
  <div>
    <el-card class="cards">
      <CategorySelect
        @getCategoryId="getCategoryId"
        :show="!isShowTable"
      ></CategorySelect>
    </el-card>
    <el-card class="cards">
      <!--属性展示的表格-->
      <div v-show="isShowTable">
        <el-button
          type="primary"
          icon="el-icon-plus"
          style="margin-bottom: 10px"
          :disabled="!c3Id"
          @click="addAttr"
          >添加</el-button
        >
        <el-table style="width: 100%" border :data="attrList">
          <el-table-column
            type="index"
            label="序号"
            width="80px"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="attrName"
            label="属性名"
            width="150px"
          ></el-table-column
          ><el-table-column prop="prop" label="属性值列表" width="width">
            <template slot-scope="{ row, $index }">
              <el-tag
                type="success"
                v-for="attrValue in row.attrValueList"
                :key="attrValue.id"
                style="margin-right: 10px"
              >
                {{ attrValue.valueName }}
              </el-tag>
            </template> </el-table-column
          ><el-table-column
            prop="prop"
            label="操作"
            width="180px"
            align="center"
          >
            <template slot-scope="{ row, $index }">
              <a title="修改" style="margin-right: 10px">
                <el-button
                  type="warning"
                  icon="el-icon-edit"
                  size="mini"
                  @click="updateAttr(row)"
                >
                </el-button>
              </a>
              <a title="删除">
                <el-button type="danger" icon="el-icon-delete" size="mini">
                </el-button>
              </a>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--添加和修改属性的界面-->
      <div v-show="!isShowTable">
        <el-form ref="form" :inline="true" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名:">
            <el-input
              placeholder="请输入属性名"
              v-model="attrInfo.attrName"
              @blur="checkName"
              @keyup.native.enter="checkName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addAttrValue"
          :disabled="!attrInfo.attrName"
          >添加属性值</el-button
        >
        <el-button icon="el-icon-close" @click="isShowTable = true"
          >取消操作</el-button
        >
        <el-table
          style="width: 100%; margin: 20px 0"
          border
          :data="attrInfo.attrValueList"
        >
          <el-table-column
            type="index"
            label="序号"
            width="80px"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称" width="width">
            <template slot-scope="{ row, $index }">
              <el-input
                v-model="row.valueName"
                size="mini"
                placeholder="请输入属性值名称"
                v-if="row.flag"
                @blur="toLook(row)"
                @keyup.native.enter="toLook(row)"
                :ref="$index"
              ></el-input>
              <span v-else @click="toEdit(row, $index)" class="span-blur">{{
                row.valueName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-popconfirm
                :title="`确认删除${row.valueName}?`"
                @onConfirm="deleteValue($index)"
              >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  slot="reference"
                ></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          @click="addOrUpdateAttr"
          :disabled="attrInfo.attrValueList.length < 1"
          >保存</el-button
        >
        <el-button @click="isShowTable = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "Attr",
  data() {
    return {
      c1Id: "",
      c2Id: "",
      c3Id: "",
      attrList: [],
      isShowTable: true, //控制table显示与隐藏
      //收集新增属性或者修改属性使用的变量
      attrInfo: {
        attrName: "", //属性名
        attrValueList: [
          //属性值，每一个属性值都是一个对象
        ],
        categoryId: 0,
        categoryLevel: 3,
      },
    };
  },
  methods: {
    //自定义事件回调
    getCategoryId({ cId, level }) {
      if (level == 1) {
        this.c1Id = cId;
        this.c2Id = "";
        this.c3Id = "";
      } else if (level == 2) {
        this.c2Id = cId;
        this.c3Id = "";
      } else {
        this.c3Id = cId;
        this.getAttrList();
      }
    },
    //获取平台属性的数据
    async getAttrList() {
      const { c1Id, c2Id, c3Id } = this;
      let result = await this.$API.attr.reqAttrList(c1Id, c2Id, c3Id);
      if (result.code == 200) {
        this.attrList = result.data;
      }
    },
    //添加属性值的回调
    addAttrValue() {
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id, //属性名ID
        valueName: "",
        flag: true, //控制每个属性的查看与编辑
      });
      //自动聚焦
      this.$nextTick(() => {
        this.$refs[this.attrInfo.attrValueList.length - 1].focus();
      });
    },
    //添加按钮的回调
    addAttr() {
      this.isShowTable = false;
      //清空数据,并收集三级分类ID
      this.attrInfo = {
        attrName: "", //属性名
        attrValueList: [
          //属性值，每一个属性值都是一个对象
        ],
        categoryId: this.c3Id,
        categoryLevel: 3,
      };
    },
    //修改某个属性
    updateAttr(row) {
      this.isShowTable = false;
      this.attrInfo = JSON.parse(JSON.stringify(row));
      this.attrInfo.attrValueList.forEach((element) => {
        //element.flag=false
        //这样不可以。因为vue无法探测普通的新增property，这样的数据不是响应式的
        this.$set(element, "flag", false);
      });
    },
    //修改属性时失去焦点的回调
    toLook(row) {
      //用户新增的属性值不能为空
      if (row.valueName.trim() == "") {
        row.valueName = "";
        this.$message({
          message: "请输入属性值",
          type: "warning",
        });
        return;
      }
      //用户新增的属性值不应该重复
      let isRepat = this.attrInfo.attrValueList.some((element) => {
        //将最新添加的属性值从判断序列中刨除
        if (row !== element) {
          return row.valueName == element.valueName;
        }
      });
      if (isRepat) {
        row.valueName = "";
        this.$message({
          message: "请勿添加重复的属性值",
          type: "warning",
        });
        return;
      }
      row.flag = false;
    },
    //点击span变为编辑模式
    toEdit(row, index) {
      row.flag = true;
      //因为v-if的使用所以导致点击span时input并不会马上渲染
      this.$nextTick(() => {
        this.$refs[index].focus();
      });
    },
    //检查属性名是否为空或与其他属性名重复
    checkName() {
      //用户新增的属性名不能为空
      if (this.attrInfo.attrName.trim() == "") {
        this.attrInfo.attrName = "";
        this.$message({
          message: "请输入属性名",
          type: "warning",
        });
        return;
      }
      //用户新增的不应该重复
      let isRepat = this.attrList.some((element) => {
        if (this.attrInfo.id !== element.id) {
          return this.attrInfo.attrName == element.attrName;
        }
      });
      if (isRepat) {
        this.attrInfo.attrName = "";
        this.$message({
          message: "请勿添加重复的属性名",
          type: "warning",
        });
        return;
      }
    },
    //气泡确认框确认按钮回调
    deleteValue(index) {
      this.attrInfo.attrValueList.splice(index, 1);
    },
    //修改或添加的保存按钮
    async addOrUpdateAttr() {
      //整理参数
      //1.用户添加了很多属性值且为空,不应该提交
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter(
        (element) => {
          if (element.valueName != "") {
            //2.提交的数据中不应该有flag
            delete element.flag;
            return true;
          }
        }
      );
      //如果属性名或者属性值中有空的，则不可以进行提交
      if (
        this.attrInfo.attrValueList.length < 1 ||
        this.attrInfo.attrName == ""
      ) {
        this.$message.error("保存失败,请检查内容是否有缺漏");
        this.attrInfo.attrValueList.forEach((element) => {
          //再把flag安回去
          this.$set(element, "flag", false);
        });
        return;
      }
      try {
        await this.$API.attr.reqAddOrUpdateAttr(this.attrInfo);
        this.$message({ type: "success", message: "保存成功" });
        this.getAttrList();
        this.isShowTable = true;
      } catch (error) {
        this.$message.error("保存失败");
      }
    },
  },
};
</script>

<style lang="css" scoped>
.cards {
  margin: 20px 0;
}
.span-blur {
  display: inline-block;
  width: 100%;
}
</style>
